 //
//  PortraitsViewController.m
//  ProjectB
//
//  Created by lanou on 16/5/5.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "PortraitsViewController.h"
#import "QBImagePicker/QBImagePicker.h"
#import <SVProgressHUD.h>
#import "PortraitsTableViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>

#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height
#define KOriginalPhotoImagePath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"OriginalPhotoImages"]


@interface PortraitsViewController ()<UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, QBImagePickerControllerDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) NSIndexPath *cellIndex;
@property (nonatomic, assign) BOOL isCont;
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, strong) NSMutableDictionary *listDic;

@end

@implementation PortraitsViewController

/**
 *  懒加载
 *
 *  @return 各自的返回值
 */

- (NSMutableDictionary *)listDic {
    if (!_listDic) {
        _listDic = [[NSMutableDictionary alloc] init];
    }
    return _listDic;
}

- (NSIndexPath *)cellIndex {
    if (!_cellIndex) {
        _cellIndex = [[NSIndexPath alloc] init];
    }
    return _cellIndex;
}

- (BOOL)isCont {
    if (!_isCont) {
        _isCont = YES;
    }
    return _isCont;
}

- (BOOL)isOpen {
    if (!_isOpen) {
        _isOpen = NO;
    }
    return _isOpen;
}

/**
 *  懒加载结束
 */

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.items.firstObject.backBarButtonItem = [UIBarButtonItem createBackItem];
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    self.view.backgroundColor = [UIColor whiteColor];
    NSLog(@"%@", NSHomeDirectory());
//    [self addView];
    self.title = @"肖像馆";
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(addPic)]; // 添加按钮
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"shareB"] style:0 target:self action:@selector(shareImg)];
    NSArray *btnArr = [NSArray arrayWithObjects:right, left, nil];
    [self.navigationItem setRightBarButtonItems:btnArr];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"PortraitsTableViewCell" bundle:nil] forCellReuseIdentifier:@"imgCell"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapT)];
    [self.tableView addGestureRecognizer:tap];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self.tableView addGestureRecognizer:longPress];
    [self.view addSubview:_tableView];
    
}

- (void)shareImg {
    NSLog(@"分享图片");
}

- (void)tapT {
    if (_isOpen) {
        
        NSDateFormatter *formatterY = [[NSDateFormatter alloc] init];
        formatterY.dateFormat = @"yyyy";
        NSString *yearString = [formatterY stringFromDate:_datePicker.date];
        NSDateFormatter *formatterM = [[NSDateFormatter alloc] init];
        formatterM.dateFormat = @"MM";
        NSString *monString = [formatterM stringFromDate:_datePicker.date];
        NSDateFormatter *formatterD = [[NSDateFormatter alloc] init];
        formatterD.dateFormat = @"dd";
        NSString *dayString = [formatterD stringFromDate:_datePicker.date];
        NSDateFormatter *formatterS = [[NSDateFormatter alloc] init];
        formatterS.dateFormat = @"yyyy-MM-dd";
        NSString *sortString = [formatterS stringFromDate:_datePicker.date];
        NSArray *keys = [_listDic allKeys];
        NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
        NSURL *url = [[(NSMutableArray *)[_listDic objectForKey:[sortedArr objectAtIndex:_cellIndex.section]] objectAtIndex:_cellIndex.row] objectForKey:@"url"];
        NSData *image = [[(NSMutableArray *)[_listDic objectForKey:[sortedArr objectAtIndex:_cellIndex.section]] objectAtIndex:_cellIndex.row] objectForKey:@"image"];
        [(NSMutableArray *)[_listDic objectForKey:[sortedArr objectAtIndex:_cellIndex.section]] removeObjectAtIndex:_cellIndex.row];
        NSMutableArray *arr = [_listDic objectForKey:sortedArr[_cellIndex.section]];
        if (arr.count == 0) {
            [_listDic removeObjectForKey:sortedArr[_cellIndex.section]];
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:_cellIndex.section] withRowAnimation:UITableViewRowAnimationRight];
        }
        NSDictionary *tempDic = @{@"mon" : monString, @"day" : dayString, @"url" : url, @"sort" : sortString, @"image" : image};
        if (![[_listDic allKeys] containsObject:yearString]) {
            NSMutableArray *arr = [[NSMutableArray alloc] init];
            [self.listDic setValue:arr forKey:yearString];
        }
        [[_listDic valueForKey:yearString] addObject:tempDic];
        
        NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES]];
        [[_listDic valueForKey:yearString] sortUsingDescriptors:sortDescriptors];
        
        [_tableView reloadData];
        [_datePicker removeFromSuperview];
        _isOpen = NO;
    }
}

- (void)longPress:(UILongPressGestureRecognizer *)receiver {
    CGPoint p = [receiver locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
    self.cellIndex = indexPath;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];

    UIAlertAction *changeDate = [UIAlertAction actionWithTitle:@"修改相片日期" style:0 handler:^(UIAlertAction * _Nonnull action) {

        UIViewController *dateVC = [[UIViewController alloc] init];
        dateVC.view.frame = [UIScreen mainScreen].bounds;
        
        dateVC.view.backgroundColor = [UIColor blackColor];
        dateVC.view.alpha = 0.5;
        
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, kScreenHeight - 220, kScreenWidth, 220)];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        NSArray *keys = [_listDic allKeys];
        NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
        NSMutableArray *arr = [_listDic objectForKey:sortedArr[indexPath.section]];
        NSDictionary *dic = [arr objectAtIndex:_cellIndex.row];
        NSString *str = [dic objectForKey:@"sort"];
        NSDateFormatter *formatterS = [[NSDateFormatter alloc] init];
        formatterS.dateFormat = @"yyyy-MM-dd";
        NSDate *date = [formatterS dateFromString:str];
        _datePicker.date = date;
        
        [self.view addSubview:_datePicker];
        _isOpen = YES;
        
    }];
    
    UIAlertAction *delete = [UIAlertAction actionWithTitle:@"删除相片" style:2 handler:^(UIAlertAction * _Nonnull action) {
        NSArray *keys = [_listDic allKeys];
        NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
        [[_listDic objectForKey:sortedArr[indexPath.section]] removeObjectAtIndex:indexPath.row];
        NSMutableArray *arr = [_listDic objectForKey:sortedArr[indexPath.section]];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
        if (arr.count == 0)  {
            [_listDic removeObjectForKey:sortedArr[indexPath.section]];
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
        }
        
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    [alert addAction:changeDate];
    [alert addAction:delete];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
    
}

// 点击添加按钮后
- (void)addPic {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择图片来源" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    // 相机
    UIAlertAction *cam = [UIAlertAction actionWithTitle:@"相机" style:0 handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.allowsEditing = YES;
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
        } else {
            [SVProgressHUD showErrorWithStatus:@"设备无相机"];
        }
        
    }];
    // 相册
    UIAlertAction *picLib = [UIAlertAction actionWithTitle:@"图库" style:0 handler:^(UIAlertAction * _Nonnull action) {
        QBImagePickerController *qbImg = [[QBImagePickerController alloc] init];
        qbImg.delegate = self;
        qbImg.allowsMultipleSelection = YES;
        [self presentViewController:qbImg animated:YES completion:nil];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    [alert addAction:cam];
    [alert addAction:picLib];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

// 相机
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSLog(@"------info is %@", info);
    UIImage *img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatterY = [[NSDateFormatter alloc] init];
    formatterY.dateFormat = @"yyyy";
    NSString *yearString = [formatterY stringFromDate:date];
    NSDateFormatter *formatterM = [[NSDateFormatter alloc] init];
    formatterM.dateFormat = @"MM";
    NSString *monString = [formatterM stringFromDate:date];
    NSDateFormatter *formatterD = [[NSDateFormatter alloc] init];
    formatterD.dateFormat = @"dd";
    NSString *dayString = [formatterD stringFromDate:date];
    NSDateFormatter *formatterS = [[NSDateFormatter alloc] init];
    formatterS.dateFormat = @"yyyy-MM-dd";
    NSString *sortString = [formatterS stringFromDate:date];
    if (![[_listDic allKeys] containsObject:yearString]) {
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        [self.listDic setValue:arr forKey:yearString];
    }
    NSURL* url = [info objectForKey:UIImagePickerControllerMediaURL];
    NSDictionary *tempDic = @{@"mon" : monString, @"day" : dayString, @"url" : url, @"sort" : sortString};
    [[_listDic valueForKey:yearString] addObject:tempDic];
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES]];
    [[_listDic valueForKey:yearString] sortUsingDescriptors:sortDescriptors];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self.tableView reloadData];
    
}

// 相册
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
    for (PHAsset *asset = assetsFetchResults[0] in assets) {
        NSDate *date = asset.creationDate;
        NSDateFormatter *formatterY = [[NSDateFormatter alloc] init];
        formatterY.dateFormat = @"yyyy";
        NSString *yearString = [formatterY stringFromDate:date];
        NSDateFormatter *formatterM = [[NSDateFormatter alloc] init];
        formatterM.dateFormat = @"MM";
        NSString *monString = [formatterM stringFromDate:date];
        NSDateFormatter *formatterD = [[NSDateFormatter alloc] init];
        formatterD.dateFormat = @"dd";
        NSString *dayString = [formatterD stringFromDate:date];
        NSDateFormatter *formatterS = [[NSDateFormatter alloc] init];
        formatterS.dateFormat = @"yyyy-MM-dd";
        NSString *sortString = [formatterS stringFromDate:date];

        [imageManager requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:0 options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            
            // 添加图片以及之后的动作
            
            NSData *imgData = UIImagePNGRepresentation(result);
            
            NSURL *url = [info objectForKey:@"PHImageFileURLKey"];

            NSArray *arr = [_listDic allKeys];
            for (int i = 0; i < arr.count; i++) {
                for (NSDictionary *dic in [_listDic valueForKey:arr[i]]) {
                    NSURL *str = [dic objectForKey:@"url"];
                    if ([str isEqual:url]) {
                        _isCont = YES;
                    }
                }
                
            }
            if (_isCont == YES) {
                [SVProgressHUD showInfoWithStatus:@"有照片已存在"];
                _isCont = NO;
            } else if (_isCont == NO) {
                if (![[_listDic allKeys] containsObject:yearString]) {
                    NSMutableArray *arr = [[NSMutableArray alloc] init];
                    [self.listDic setValue:arr forKey:yearString];
                }
                
                NSDictionary *tempDic = @{@"mon" : monString, @"day" : dayString, @"url" : url, @"sort" : sortString, @"image" : imgData};

                [[_listDic valueForKey:yearString] addObject:tempDic];
                NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"sort" ascending:YES]];
                [[_listDic valueForKey:yearString] sortUsingDescriptors:sortDescriptors];
                
                [self.tableView reloadData];
            }
            
            
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *keys = [_listDic allKeys];
    NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *arr = [_listDic objectForKey:sortedArr[section]];
    return arr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [_listDic allKeys].count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *keys = [_listDic allKeys];
    NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
    return [sortedArr objectAtIndex:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PortraitsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"imgCell" forIndexPath:indexPath];
    NSArray *keys = [_listDic allKeys];
    NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
    NSArray *arr = [_listDic objectForKey:sortedArr[indexPath.section]];
    NSDictionary *dic = [arr objectAtIndex:indexPath.row];
    UIImage *img = [UIImage imageWithData:[dic objectForKey:@"image"]];
    cell.imageV.image = img;
    cell.frame = CGRectMake(0, 0, kWidth, kWidth * img.size.height / img.size.width);
    
    NSString *dayDate = [dic objectForKey:@"day"];
    int month = [[dic objectForKey:@"mon"] intValue];
    NSString *monEng = [[NSString alloc] init];
    switch (month) {
        case 1:
            monEng = @"Jan";
            break;
        case 2:
            monEng = @"Feb";
            break;
        case 3:
            monEng = @"Mar";
            break;
        case 4:
            monEng = @"Apr";
            break;
        case 5:
            monEng = @"May";
            break;
        case 6:
            monEng = @"Jun";
            break;
        case 7:
            monEng = @"Jul";
            break;
        case 8:
            monEng = @"Aug";
            break;
        case 9:
            monEng = @"Sep";
            break;
        case 10:
            monEng = @"Oct";
            break;
        case 11:
            monEng = @"Nov";
            break;
        case 12:
            monEng = @"Dec";
            break;
        default:
            break;
    }
    
    cell.monLabel.text = monEng;
    cell.dayLabel.text = dayDate;
    cell.monLabel.textColor = [UIColor colorWithRed:0.977 green:0.843 blue:0.866 alpha:1.000];
    cell.dayLabel.textColor = [UIColor colorWithRed:0.977 green:0.843 blue:0.866 alpha:1.000];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    editingStyle = UITableViewCellEditingStyleDelete;
    NSArray *keys = [_listDic allKeys];
    NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
    [[_listDic objectForKey:sortedArr[indexPath.section]] removeObjectAtIndex:indexPath.row];
    NSMutableArray *arr = [_listDic objectForKey:sortedArr[indexPath.section]];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
    if (arr.count == 0) {
        [_listDic removeObjectForKey:sortedArr[indexPath.section]];
        [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
    }
    
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    
    NSArray *keys = [_listDic allKeys];
    NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *arr = [_listDic objectForKey:sortedArr[indexPath.section]];
    NSDictionary *dic = [arr objectAtIndex:indexPath.row];
    NSData *data = [dic objectForKey:@"image"];
    UIImage *img = [UIImage imageWithData:data];
    
    return kWidth * img.size.height / img.size.width;
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [self.tableView reloadData];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{
    if (!error) {
        NSLog(@"picture saved with no error.");
    }
    else
    {
        NSLog(@"error occured while saving the picture%@", error);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
